package cn.boysoft.core.log;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import cn.boysoft.core.model.MessageTypeEnum;
import cn.boysoft.core.model.message.Request;
import cn.boysoft.core.model.message.json.JSONRequest;
import cn.boysoft.core.server.MainServer;
import cn.boysoft.core.server.ServiceInfo;
/**
 * @author 付厚俊
 * CreateTime 2013-4-4 下午5:22:47
 */
@Aspect  
@Component 
public class LogInterceptor {
	@Autowired
	OperateLogManager operateLogManager;

	@SuppressWarnings("unchecked")
	@Around(value ="execution(* cn.boysoft.core.handler.impl.DefaultBusinessHandler.execute(..))")
	public Object around(ProceedingJoinPoint point) throws Throwable {
		String logKeyword = "";
		OperateLogEntity operateLogEntity = new OperateLogEntity();
		long start = System.currentTimeMillis();
		Object arg = point.getArgs()[0];
		if(arg instanceof JSONRequest){
			operateLogEntity.setMessageType(MessageTypeEnum.JSON);
		}else{
			operateLogEntity.setMessageType(MessageTypeEnum.XML);
		}
		Request request = (Request)arg;
		String commandId = request.getServiceId();
		ServiceInfo serviceInfo =  MainServer.getOnlyReadServiceInfo(commandId);
		Object data = null;
		if(serviceInfo != null){
			@SuppressWarnings("unused")
			Object service = MainServer.getBean(serviceInfo.getServiceClassId());
			if(serviceInfo.getDataClazz() != null){
				data = request.getData();
			}
		}
		Object retVal = point.proceed();
		long end = System.currentTimeMillis();
		if(data instanceof OperateLogKeyword){
			OperateLogKeyword operateLogKeyword = (OperateLogKeyword)data;
			logKeyword = operateLogKeyword.getOperateLogKeyword();
		}else if(data  instanceof String){
			logKeyword = (String)data;
		}
		operateLogEntity.setServiceName(serviceInfo.getServiceName());
		operateLogEntity.setData(data);
		operateLogEntity.setExecuteTime(end - start);
		operateLogEntity.setKeyword(logKeyword);
		operateLogEntity.setCreatedById(request.getOperateId());
		operateLogEntity.setServiceId(commandId);
		operateLogManager.recordOperateLog(operateLogEntity);
		return retVal;
	}

//	@AfterThrowing(value ="execution(* cn.boysoft.core.handler.impl.DefaultBusinessHandler.execute(..))")
//	public void throwing(){
//		
//	}

}
